package com.example.auth.datasource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.DeclareAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
 * 多数据源切面
 */
@Aspect
@Component
public class DatasourceAspect {

    private Logger logger = LoggerFactory.getLogger(DatasourceAspect.class);
    @Before("@annotation(dataSourceKey) && execution(* com.example.auth.datasource.*.*(..))")
    public void beforeSwitchDataSource(JoinPoint joinPoint,  DataSourceKey dataSourceKey) {
        String key = dataSourceKey.value();
        logger.info("key:{}",key);
        DataSourceContextHolder.setDataSourceKey(key);
    }

    @Before("@annotation(dataSourceKey) && execution(* com.example.auth.service.*.*(..))")
    public void beforeServiceSwitchDataSource(JoinPoint joinPoint,  DataSourceKey dataSourceKey) {
        String key = dataSourceKey.value();
        logger.info("key:{}",key);
        DataSourceContextHolder.setDataSourceKey(key);
    }

    @After("@annotation(dataSourceKey) && execution(* com.example.auth.service.*.*(..))")
    public void afterServiceSwitchDataSource(JoinPoint joinPoint,  DataSourceKey dataSourceKey) {
        String key = dataSourceKey.value();
        logger.info("key:{}",key);
        DataSourceContextHolder.clearDataSourceKey();
    }

    @After("@annotation(dataSourceKey) && execution(* com.example.auth.datasource.*.*(..)) ")
    public void afterSwitchDataSource(JoinPoint joinPoint, DataSourceKey dataSourceKey) {
        logger.info("key:{}",dataSourceKey.value());
        DataSourceContextHolder.clearDataSourceKey();
    }

}
